package com.weishi.project.speedometer.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.weishi.common.enums.RedisConstants;
import com.weishi.common.utils.GPSUtil;
import com.weishi.framework.redis.RedisCache;
import com.weishi.framework.web.domain.AjaxResult;
import com.weishi.project.speedometer.service.ISpeedometerService;
import com.weishi.project.speedometer.vo.RealTimeDataVo;
import com.weishi.project.training.domain.ShipSpeedRecordLog;
import com.weishi.project.training.service.IShipSpeedRecordLogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class SpeedometerServiceImpl implements ISpeedometerService {

    @Autowired
    private RedisCache redisCache;

    /**
     * 船速仪实时数据 接口
     */
    @Autowired
    private IShipSpeedRecordLogService shipSpeedRecordLogService;

    /**
     * 根据船速仪 id 查询船速仪
     */
    @Override
    public AjaxResult selectRealTimeDataListById(String id) {
        List<ShipSpeedRecordLog> shipSpeedRecordLogList = shipSpeedRecordLogService.list(Wrappers.<ShipSpeedRecordLog>lambdaQuery().orderByDesc(ShipSpeedRecordLog::getId));

        double mm = GPSUtil.GetDistance1(shipSpeedRecordLogList.get(0).getLongitude(), shipSpeedRecordLogList.get(0).getLatitude(), shipSpeedRecordLogList.get(1).getLongitude(), shipSpeedRecordLogList.get(1).getLatitude());
        System.out.println(shipSpeedRecordLogList.get(0));
        System.out.println(shipSpeedRecordLogList.get(1));
        RealTimeDataVo realTimeDataVo = new RealTimeDataVo();
        realTimeDataVo.setDistance(mm);
        realTimeDataVo.setTime(0);

        return AjaxResult.success(realTimeDataVo);
    }

    @Override
    public void addRealTimeData(ShipSpeedRecordLog shipSpeedRecordLog) {
        //更新船速仪状态 5秒
        redisCache.setCacheObject(RedisConstants.ShipSpeed_Status_Prefix + shipSpeedRecordLog.getShipSpeedSn(), 1, 5, TimeUnit.SECONDS);

        //入库存储
        if (redisCache.getCacheObject(RedisConstants.Channel_ShipSpeed_Status_Prefix + shipSpeedRecordLog.getShipSpeedSn()) != null) {
            int channelId = redisCache.getCacheObject(RedisConstants.Channel_ShipSpeed_Status_Prefix + shipSpeedRecordLog.getShipSpeedSn());
            shipSpeedRecordLog.setChannelId(channelId);
            shipSpeedRecordLog.setCtime(new Date());
            shipSpeedRecordLogService.save(shipSpeedRecordLog);
        }
    }
}
